<?php

namespace App\Admin\Controllers;

use App\Admin\Controllers\Helpers\LinkHelper;
use App\Constant\GroupEnum;
use App\Models\Group;
use App\Models\Setting;
use App\Models\User;
use App\Services\Group\GroupService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Show;
use Illuminate\Support\Facades\DB;

class GroupController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Group(), function (Grid $grid) {
            $grid->model()->orderBy('created_at', 'desc');
            $grid->model()->with(['owner'])->withCount('members');
            $grid->quickSearch('id', 'user_id','owner.uuid','owner.nickname')->placeholder('输入 id\uuid\用户昵称\uid')->auto(false);;

            // $grid->column('id')->sortable();
            $grid->column('user_id')
                ->width('250px')
                ->display(function () {
                    return LinkHelper::displayUser($this->owner);
                });
            $grid->column('parent', '来源/上级')
                ->display(function () {
                    $user = $this->owner;
                    $text = '';
                    if ($user) {
                        $user->load(['parent', 'member', 'member.leader:id,uuid,nickname']);
                        $parent = $user->parent;
                        $leader = $user->member->leader ?? '';

                        $text = '<i>-</i>';
                        if ($parent) {
                            $text = "师傅: <a href='?id={$parent->id}'>{$parent->nickname}｜<b>{$parent->uuid}</b></a>";
                        }
                        if ($leader) {
                            $text .= "<br/> 团长: <a href='?id={$leader->id}'>{$leader->nickname}｜<b>{$leader->uuid}</a>";
                        }
                    }
                    return "<div style='font-size: smaller'>{$text}</div>";
                });
//            $grid->column('phone', '登录账号')
//                ->display(function () {
//                    return $this->owner->phone ?? '';
//                });
//            $grid->column('password', '密码')
//                ->display(function () {
//                    return $this->owner->dip ?? '';
//                });

            $grid->column('members')->display(function ($members) {
                return sprintf("<a href='group-members?leader_id={$this->user_id}'>%s</a>", $this->members_count);
            });
            $grid->column('owner.is_advanced_group', '团长类型')
                ->using(GroupEnum::GROUP_TYPES)
                ->label(GroupEnum::GROUP_COLORS);
            $grid->column('created_at')->sortable();

            $grid->disableBatchDelete();
            $grid->disableViewButton();

            $grid->setActionClass(Grid\Displayers\Actions::class);

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Group(), function (Show $show) {
            $show->field('id');
            $show->field('user_id');
            $show->field('created_by');
            $show->field('members');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Group(), function (Form $form) {
            $owner = $form->model()->load('owner')->owner ?? '';
            $form->display('id');
            $form->select('user_id')
                ->required()
                ->options(
                    User::query()->selectRaw(DB::raw('id, concat(uuid, "-", nickname) as uuid'))
                        ->pluck('uuid', 'id')
                );
//            $form->text('phone', '登录账号')->value($owner->phone ?? '')->required();
//            $form->display('owner.dip', '登录密码');
//            $form->text('password')->required();
            $form->hidden('created_by')->value(GroupEnum::CREATED_BY_GRANTED);
            $form->radio('owner.is_advanced_group', '团长类型')
                ->required()
                ->default(GroupEnum::GROUP_TYPE_NORMAL)
                ->options(GroupEnum::GROUP_TYPES);

            $form->display('created_at');
            $form->display('updated_at');
//修改团长
            $form->submitted(function (Form $form) {
                $group = Setting::get('group');
                $enabled = $group['enabled'] ?? 0;
                if (!$enabled) {
                    return $form->response()->error('团长功能已禁用，请先打开该功能');
                }
                /** @var User $user */
                $user = User::query()->findOrFail($form->input('user_id'));
                GroupService::make($user, []);
                if (request()->post('owner')['is_advanced_group'] ?? 0) {
                    $user->update(['is_advanced_group' => 1]);
                } else {
                    $user->update(['is_advanced_group' => 0]);
                }
           //     $user->update(['dip' => $form->input('password')]);

                return $form->response()->success('操作成功')->redirect('groups');
            });
//删除团长
            $form->deleting(function (Form $form) {
                $group = Setting::get('group');
                $enabled = $group['enabled'] ?? 0;
                if (!$enabled) {
                    return $form->response()->error('团长功能已禁用，请先打开该功能');
                }

                $items = $form->model()->toArray();
                foreach ($items as $item) {
                    if (isset($item['user_id'])) {
                        /** @var User $user */
                        $user = User::query()->findOrFail($item['user_id']);
                        GroupService::remove($user);
                        $user->update(['is_advanced_group' => 0]);
                    }
                }

                return $form->response()->success('操作成功')->redirect('groups');
            });
        });
    }
}
